<?php
require('dbconnection.php');
require('selectableImage.php');
class Image{

  private $matchingTerm;
  private $images;
  

  // The constructor is after the private functions
  // This is a really poor thing about PHP



  private function setMacthingTerm($termID){
    // Query to get the matching term
    $queryMatchingTerm="select term from terms ".
      "where terms.picid=$termID and ".
      "top ='1' limit 1";
    $resultMatchingTerm = mysql_query($queryMatchingTerm);
    if (!$resultMatchingTerm)
      throw new Exception("There is no answer term returned");    

    $resultMatching = mysql_fetch_row($resultMatchingTerm);
    $this->matchingTerm = $resultMatching[0];
  }

  private function getAnswer(){
    $ansQuery="select pictures.id,path,term ".
      "from pictures,terms ".
      "where pictures.id =terms.picid and  " .
      "terms.top ='0' order by rand() limit 1";

    $resultAnswerQuery = mysql_query($ansQuery);
    if (!$resultAnswerQuery)
      throw new Exception("There is no answer image returned");    
    $resultAnswer = mysql_fetch_row($resultAnswerQuery);
    // Add the answer to the images array
    $this->images[] = new SelectableImage($resultAnswer[1],$resultAnswer[2]);

    return $resultAnswer[0];

  }
 
  private function setDistractors($termID){
    // Get the destracting images NOTE LIMIT 5!!!!!!!!!!!!!!!
    $queryDestractors="select DISTINCT path, term ".
      "from pictures, terms ".
      "where  terms.picid <> $termID and terms.top=0 and ".
      "terms.picid =pictures.id ".
      "order by rand()  limit 5";

    $resultDestractors = mysql_query($queryDestractors);
    if (!$resultDestractors)
      throw new Exception("There is no destractors returned");    
    

    // This gets the distractor images
    while($result = mysql_fetch_row($resultDestractors)){
      $this->images[] = new SelectableImage($result[0],$result[1]);
    }
  }


  public function Image(){
    db_connect();
    $answerPictureID = $this->getAnswer();
    $this->setMacthingTerm($answerPictureID);
    $this->setDistractors($answerPictureID);
    // Randomise the array so answer not predictable
    shuffle($this->images); 
  }

  public function getMatchingTerm(){
    return $this->matchingTerm;
  }

  public function getImages(){
    return $this->images;
  }
}



?>
